/*
 *
 *      Copyright (c) 2018-2025, shenghua All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: shenghua
 *
 */

package com.chen.root.base;

import com.chen.root.constant.CommonCons;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author shenghua
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ApiModel(value = "响应信息主体")
public final class R<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	/** code：0-成功，1-失败 */
	@ApiModelProperty(value = "code：0-成功，1-失败")
	private int code;

	/** 成功标识：true-成功，false-失败 */
	@ApiModelProperty(value = "成功标识：true-成功，false-失败")
	private boolean success;

	/** 返回信息 */
	@ApiModelProperty(value = "返回信息")
	private String msg;

	/** 数据 */
	@ApiModelProperty(value = "数据")
	private T data;

	public static <T> R<T> ok() {
		return ok(null, "OK");
	}

	public static <T> R<T> ok(T data) {
		return ok(data, "OK");
	}

	public static <T> R<T> ok(T data, String msg) {
		return buildResult(data, CommonCons.SUCCESS, msg);
	}

	public static <T> R<T> failed() {
		return failed(null, "FAILED");
	}

	public static <T> R<T> failed(String msg) {
		return failed(null, msg);
	}

	public static <T> R<T> failed(T data, String msg) {
		return buildResult(data, CommonCons.FAIL, msg);
	}

	private static <T> R<T> buildResult(T data, int code, String msg) {
		R<T> r = new R<>();
		r.setCode(code);
		r.setData(data);
		r.setMsg(msg);
		r.setSuccess(code == CommonCons.SUCCESS);
		return r;
	}

}
